package com.ooo.sdkdemo;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.blankj.utilcode.util.AppUtils;
import com.traceless.gamesdk.TracelessGamesApi;
import com.traceless.gamesdk.open.bean.GameRoleData;
import com.traceless.gamesdk.open.bean.PayData;
import com.traceless.gamesdk.open.bean.SDKConfig;
import com.traceless.gamesdk.open.interfaces.OnAccountSwitchEventListener;
import com.traceless.gamesdk.open.interfaces.OnFcmListener;
import com.traceless.gamesdk.open.interfaces.OnGameExitListener;
import com.traceless.gamesdk.open.interfaces.OnInitListener;
import com.traceless.gamesdk.open.interfaces.OnLoginListener;
import com.traceless.gamesdk.open.interfaces.OnLogoutListener;
import com.traceless.gamesdk.open.interfaces.OnPayListener;
import com.traceless.gamesdk.open.interfaces.OnPublicListener;
import com.traceless.gamesdk.open.interfaces.OnSynchroniGameDataListener;
import com.traceless.gamesdk.open.interfaces.OnUserAgreementListener;
import com.traceless.gamesdk.ui.activity.ContainerActivity;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;




public class MainActivity extends Activity {

    public  String TAG = "Traceless";

    private MainActivity mActivity;

    private String uid;
    private String fcm;
    TextView mTv;
    EditText mEtPicet;
    String server = "1";//FIXME  注意此字符串必須是可轉換成数字的字符串！




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TracelessGamesApi.getInstance().onCreate(MainActivity.this);

        this.mActivity = this;

        for ( String sha1 : AppUtils.getAppSignaturesSHA1() ) {
            Log.e("sha1:", sha1 );
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTv = (TextView) findViewById(R.id.tv_main);
        mEtPicet = (EditText) findViewById(R.id.et_picet);


        //首次打开会弹出用户协议页面 用户同意后之后打开不会弹出协议 而是直接回调agree
        //用户拒绝则会退出APP SDK内已处理
        TracelessGamesApi.getInstance().showUserAgreement( mActivity, new OnUserAgreementListener() {
            @Override
            public void agree() {
                //用户同意协议后初始化SDK
                iniSDK();
            }
        });


    }


    private void iniSDK(){

        /*監聽SDK新消息提醒*/
        TracelessGamesApi.getInstance().setNewMessageReminderListener(new OnPublicListener<Integer>() {
            @Override
            public void onCallback(Integer integer) {
                Log.d(TAG,"未讀消息數量"+integer);
            }
        });
        /*切換賬戶監聽*/
        TracelessGamesApi.getInstance().setAccountSwitchListener(new OnAccountSwitchEventListener() {
            @Override
            public void accountSwitch(String userId, String userToken, boolean isFCM) {
                uid = userId;
                mTv.setText("SDK要求切換登入 uid==" + uid + " token==" + userToken);
            }
        });

        /*監聽SDK內退出賬號的操作*/
        TracelessGamesApi.getInstance().setLogoutListener(new OnLogoutListener() {
            @Override
            public void logout(String userId) {
                /**
                 * 遊戲需要在收到這個回調后  執行賬戶退出，並回到遊戲的登入界面
                 */
                TracelessGamesApi.getInstance().login( mActivity , onLoginListener);
                mTv.setText("sdk 點擊退出，遊戲執行註銷並跳轉到登入界面操作");
            }
        });



        findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TracelessGamesApi.getInstance().login(mActivity, onLoginListener );
            }
        });

        findViewById(R.id.test_verify_realname_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TracelessGamesApi.getInstance().openFcm(MainActivity.this, new OnFcmListener() {
                    @Override
                    public void success() {
                        mTv.setText("實名認證成功");
                    }
                    @Override
                    public void fail() {
                        mTv.setText("實名認證失敗");
                    }
                });
            }
        });

        findViewById(R.id.btn_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String amount=mEtPicet.getText().toString();

                //調用支付接口時創建PayData()實體類,將支付參數封裝到該實體類
                PayData payData = new PayData();
                payData.setUid(uid);//用戶id
                payData.setCporder("020718544221118");//CP訂單號(測試時隨機六位數)
                // FIXME 此服務器ID 必須是當前玩家所在的遊戲區服ID，不能隨便亂填，否則會導致統計上的一系列問題！！ （注意：區服(必須是正整數)，沒有區服，傳1）
                payData.setSid(server);
                payData.setAmount(amount);//訂單金額(單位：分)
                payData.setItem_id("10000");//商品ID(可傳可不傳，不傳為空)
                payData.setItem_name("黃金月卡");//商品名稱
                payData.setExtra("8569123654");//CP透傳字段，通知CP支付結果時原樣返回
                payData.setRole_id("123321");//角色的唯一ID，4.4.2版本新增的參數
                payData.setRole_name("天下無敵");//角色名，5.2.0版本新增的參數
                TracelessGamesApi.getInstance().pay(MainActivity.this, payData, new OnPayListener() {
                    @Override
                    public void complete(String cpOrder) {
                        mTv.setText("支付完成 orderId==" + cpOrder);
                    }
                    @Override
                    public void cancel(String cpOrder) {
                        mTv.setText("取消支付  orderId==" + cpOrder );
                    }
                    @Override
                    public void fail(String cpOrder, int code, String msg) {
                        mTv.setText("支付失敗 orderId==" + cpOrder);
                    }
                });
            }
        });

        findViewById(R.id.btn_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TracelessGamesApi.getInstance().gameExit(MainActivity.this, new OnGameExitListener() {
                    @Override
                    public void exitCancel() {
                        mTv.setText("取消退出");
                    }
                    @Override
                    public void exitSuccess() {
                        mTv.setText("執行遊戲退出");
                    }
                });
            }
        });


        findViewById(R.id.btn_role).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //FIXME 注意：同步遊戲角色信息是在登入成功后 和 遊戲角色信息發生變化的時候實時提交！！！ 否則可能會導致其他問題！！！
                GameRoleData gameRoleData = new GameRoleData();
                gameRoleData.setUid(uid);//用戶id
                gameRoleData.setServer_id(server);// FIXME 此服務器ID 必須是當前玩家所在的遊戲區服ID，不能隨便亂填，否則會導致統計上的一系列問題！！ （注意：區服(必須是正整數)，沒有區服，傳1）
                gameRoleData.setServer_name("電信");//服務器名稱
                gameRoleData.setRole_id("685321");//角色ID，一個角色同一個服ID保持唯一,長度不超過50
                gameRoleData.setRole_name("一血");//角色昵稱,長度不超過50
                gameRoleData.setRole_level(10);//遊戲等級
                long time1=Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0,10));//十位時間戳
                gameRoleData.setRole_create_time(time1);//角色創建時間(單位：秒，長度：10)
                TracelessGamesApi.getInstance().synchroniGameData(MainActivity.this, gameRoleData, new OnSynchroniGameDataListener() {
                    @Override
                    public void success() {
                        mTv.setText("同步遊戲數據成功");
                    }
                    @Override
                    public void fail(int code, String msg) {
                        mTv.setText("同步遊戲數據失敗");
                    }
                });
            }
        });

        findViewById(R.id.btn_hint_ball).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TracelessGamesApi.getInstance().hideFloatball(MainActivity.this);
            }
        });

        findViewById(R.id.btn_show_ball).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TracelessGamesApi.getInstance().showFloatball(MainActivity.this);
            }
        });

        findViewById(R.id.btn_logout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TracelessGamesApi.getInstance().logout();
            }
        });
        findViewById(R.id.btn_openService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TracelessGamesApi.getInstance().openService(null);
            }
        });
        findViewById(R.id.btn_fulizx).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TracelessGamesApi.getInstance().openWelfareCentre();
            }
        });



        /**
         * 初始化 操作是使用99遊戲sdk的基礎，只有成功才可繼續使用。SDKConfig 中封裝的是 appid 。 客戶端初始化的必要參數
         */
        String appid = "androidtt";//當前僅為測試 需要運營申請
//        String serverUrl = "sdkapi.wan62.com";//测试环境
        String serverUrl = "syapi.wan62.com";//正式环境
        SDKConfig sdkConfig = new SDKConfig( appid );
        sdkConfig.setServerUrl( serverUrl );
        sdkConfig.setOrientation( 0 );//橫屏遊戲還是豎屏遊戲 0橫屏 1豎屏
        sdkConfig.setGoogleRequestIdToken("589981805341-p43kkgtmh1q5nkgbqa0gqk209d33ldda.apps.googleusercontent.com");
        sdkConfig.setFacebookApplicationId("457361052966110");
        sdkConfig.setFacebookClientToken("e3029a14c1aa7ded68c5dee4ee49472c");
        TracelessGamesApi.getInstance().initSdk(this, sdkConfig , new OnInitListener() {
            @Override
            public void success() {
                mTv.setText("sdk 初始化成功");
            }
            @Override
            public void fail(int code, String msg) {
                mTv.setText(String.format( "sdk 初始化失敗 code:%s msg:%s" , code , msg ));
            }
        });

    }



    OnLoginListener onLoginListener = new OnLoginListener() {
        @Override
        public void loginSuccess(String userId, String userToken, boolean isFCM) {
            uid = userId;
            fcm = isFCM ? "1" : "0";
            mTv.setText(String.format("登入成功uid:%s token:%s fcm:%s" , uid , userToken ,isFCM ));
        }
        @Override
        public void loginFail(int code, String msg) {
            mTv.setText("登入失敗    錯誤碼==" + code);
        }
    };


    @Override
    protected void onStart() {
        super.onStart();
        TracelessGamesApi.getInstance().onStart(MainActivity.this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        TracelessGamesApi.getInstance().onResume(MainActivity.this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        TracelessGamesApi.getInstance().onRestart(MainActivity.this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TracelessGamesApi.getInstance().onPause(MainActivity.this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        TracelessGamesApi.getInstance().onStop(MainActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TracelessGamesApi.getInstance().onDestroy(MainActivity.this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode,resultCode,data );
        TracelessGamesApi.getInstance().onActivityResult(requestCode,resultCode,data);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        TracelessGamesApi.getInstance().onRequestPermissionsResult(requestCode,permissions,grantResults);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public void onBackPressed() {
        back();
    }


    /**
     * 用戶點擊返回 物理按鈕
     */
    private void back() {
        TracelessGamesApi.getInstance().gameExit(MainActivity.this, new OnGameExitListener() {
            @Override
            public void exitCancel() {
                mTv.setText("取消退出");
            }
            @Override
            public void exitSuccess() {
                mTv.setText("執行遊戲退出");
                System.exit(0);
            }
        });
    }


}
